const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

let stars = [];
let star_num = 30;
let lastAddTime = Date.now(); // 上次增加星星的时间

function init() {
    let x = Math.random() * canvas.width;
    let y = Math.random() * canvas.height;
    let r = Math.random() * 2 + 1; // 半径
    let vx = Math.random() * 3 - 1.5; // 水平方向速度
    let vy = Math.random() * 3 - 1.5; // 垂直方向速度
    let opacity = 1; // 初始不透明度
    let decay = Math.random() * 0.002 + 0.001; // 不透明度衰减速率
    stars.push({x, y, r, vx, vy, opacity, decay});
}

function draw() {
    stars.forEach(star => {
        ctx.beginPath();
        ctx.arc(star.x, star.y, star.r, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(255, 215, 0, ${star.opacity})`; // 金色
        ctx.fill();
    });
}

function update() {
    stars.forEach(star => {
        star.x += star.vx;
        star.y += star.vy;
        star.opacity -= star.decay;
        if (star.opacity <= 0) {
            stars.splice(stars.indexOf(star), 1);
        } else {
            // 限制星星在一定范围内移动
            if (star.x < 0 || star.x > canvas.width) star.vx *= -1;
            if (star.y < 0 || star.y > canvas.height) star.vy *= -1;
        }
    });

    // 检查是否需要增加星星
    if (Date.now() - lastAddTime >= 1000 && stars.length <= star_num) {
        let numToAdd = Math.floor(Math.random() * 5) + 1;
        for (let i = 0; i < numToAdd; i++) {
            let x = Math.random() * canvas.width;
            let y = Math.random() * canvas.height;
            let r = Math.random() * 2 + 1;
            let vx = Math.random() * 3 - 1.5;
            let vy = Math.random() * 3 - 1.5;
            let opacity = 1;
            let decay = Math.random() * 0.002 + 0.001;
            stars.push({x, y, r, vx, vy, opacity, decay});
        }
        lastAddTime = Date.now();
    }
}

function animate() {
    requestAnimationFrame(animate);
    update();
    draw();
}

setTimeout(function() {
    init();
    animate();
}, 1000);


window.addEventListener('resize', () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    init();
});